﻿using XinLife.Application.Interface;
using XinLife.Model;
using XinLife.Core.Model;
using XinLife.Core.Extention;
using XinLife.Core.Helper;
using SqlSugar;
using System.Xml.Linq;

namespace XinLife.Application.Implement
{
    public class UserMsgService : BaseService, IUserMsgService
    {
        public UserMsgService(IBaseRepository baseRepository) : base(baseRepository)
        { }

        public async Task<AjaxResult> DelUserMsg(string ids)
        {
            int r = await _db.Deleteable<UserMsg>().In(ids.Split(',')).ExecuteCommandAsync();
            if (r > 0)
            {
                return Success("删除成功");
            }
            else
            {
                return Success("删除失败");
            }
        }

        public async Task<AjaxResult> EditUserMsg(UserMsg userMsg)
        {
            if (string.IsNullOrWhiteSpace(userMsg.cId))
            {
                userMsg.cSenderId = userMsg.cSenderName.IsEmpty() ? userMsg.cReceiverId : null;
                userMsg.cSenderName = userMsg.cSenderName.IsEmpty() ? userMsg.cReceiverName : userMsg.cSenderName;
                userMsg.cSenderDate = DateTime.Now;
                userMsg.cId=Guid.NewGuid().ToString("N");
                await _db.Insertable(userMsg).ExecuteCommandAsync();
                return Success("添加成功");
            }
            else
            {
                //var old = Dbers.GetInstance().SelfDber.Get<UserMsg>(userMsg.cId);
                //userMsg.cCreatedBy = old.cCreatedBy;
                //userMsg.cCreatedDate = old.cCreatedDate;
                //userMsg.Update(AspNetUser.UserId);

                //Dbers.GetInstance().SelfDber.Update(userMsg);
                return Success("修改成功");
            }
        }

        public async Task<AjaxResult> GetUnreadMsg()
        {
            var data = await _db.Queryable<UserMsg>().Where(t => t.cStatus == 0 && t.cReceiverId == AspNetUser.UserId).ToListAsync();
            return Success(data);
        }

        public async Task<AjaxResult> GetUserMsgForm(string id)
        {
            var data = await _db.Queryable<UserMsg>().FirstAsync(t => t.cId == id);
            return Success(data);
        }

        public async Task<PageData<UserMsg>> GetUserMsgPageList(Pagination page, string queryJson)
        {
            var queryParam = queryJson.ToJObject();
            string? cStatus = queryParam.Value<string>("cStatus");

            RefAsync<int> totalCount = 0;
            var users = await _db.Queryable<UserMsg>()
                     .WhereIF(!cStatus.IsEmpty(), a => a.cStatus.ToString() == cStatus && a.cReceiverId == AspNetUser.UserId)
                     .WhereIF(cStatus.IsEmpty(), a => a.cReceiverId == AspNetUser.UserId || a.cSenderId == AspNetUser.UserId)
                     .OrderBy((a) => a.cSenderDate, OrderByType.Desc)//倒序 
                     .ToPageListAsync(page.pageIndex, page.pageSize, totalCount);

            return new PageData<UserMsg>()
            {
                count = totalCount,
                entitys = users
            };
        }

        public async Task<AjaxResult> GetUsers()
        {
            var data = await _db.Queryable<User>().Where(t => t.cId != AspNetUser.UserId).Select(t => new { t.cId, t.cName }).ToDataTableAsync();
            return Success(data);
        }

        public async Task<AjaxResult> MsgReady(string ids)
        {
            if (ids == null)
            {
               await _db.Updateable<UserMsg>()
                      .SetColumns(a => a.cStatus, 1)
                      .SetColumns(a => a.cReadDate, DateTime.Now)
                      .Where("1=1")
                      .ExecuteCommandAsync();
            }
            else
            {
                string[] cids = ids.Split(',');
                await _db.Updateable<UserMsg>()
                              .SetColumns(t => t.cStatus == 1)
                              .SetColumns(t => t.cReadDate == DateTime.Now)
                              .Where(t => cids.Contains(t.cId))
                              .ExecuteCommandAsync();
            }
            return Success("ok");
        }
    }
}
